<script setup>
import ajax from '@/main';
import {SmileOutlined, DownOutlined, ExclamationCircleOutlined} from '@ant-design/icons-vue';
import {createVNode, onMounted, ref} from "vue";
import {Modal, notification} from "ant-design-vue";

const columns = [
  {
    name: '用户ID',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '用户名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '状态',
    dataIndex: 'isActive',
    key: 'isActive',
  },
  {
    title: '登录时间',
    key: 'loginTime',
    dataIndex: 'loginTime',
  },
  {
    title: '操作',
    key: 'action',
  },
];

const data = ref([]);

function getUserInfo() {
  ajax.post('/demo/userManage/userInfo').then(res => {
    if (res.data.code === 200) {
      data.value = res.data.data
    } else {
      notification['error']({
        message: '错误提示',
        description: res.data.msg,
      });
    }
  }).catch(err => {
    console.log(err)
  })

}

onMounted(() => {
  getUserInfo()
})

function formatDateTime(dateTimeStr) {
  if (dateTimeStr) {
    // 假设dateTimeStr的格式为 "YYYY-MM-DDTHH:mm:ss.sss+00:00"
    // 首先，移除时间字符串中的 "T" 和时区信息
    let dateTimeWithoutTZ = dateTimeStr.replace('T', ' ').replace(/\+\d{2}:\d{2}$/, '');

    // 分离日期和时间
    let [date, time] = dateTimeWithoutTZ.split(' ');

    // 将时间转换为小时、分钟和秒
    let [hours, minutes, seconds] = time.split(':').map(Number);

    // 加上8小时（这里不考虑夏令时或更复杂的时区转换）
    hours = (hours + 8) % 24; // 处理超过24小时的情况

    // 重新组合时间字符串
    let formattedTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

    // 返回最终格式化的日期时间字符串
    return `${date} ${formattedTime}`;
  }
}

const changeAccount = (id, state) => {
  let title;
  let content;
  if (state === 0) {
    content = '恢复后该账号将恢复正常使用';
    title = '是否要恢复该账号?';
  } else {
    title = '是否要禁用该账号?'
    content = '禁用后该账号将无法使用'
  }
  Modal.confirm({
    title: title,
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode(
        'div',
        {
          style: 'color:red;',
        },
        content,
    ),
    onOk() {
      ajax.post('/demo/userChange/changeState', {'id': id, 'isActive': state}).then(res => {
            if (res.data.code === 200) {
              getUserInfo()

            } else {
              notification['error']({
                message: '失败提示',
                description: res.data.msg,
              });
            }
          }
      )
    },
    onCancel() {
      console.log('Cancel');
    },
    class: 'test',
  });
};


const delAccount = (id) => {
  Modal.confirm({
    title: '确认要删除用户吗？',
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode(
        'div',
        {
          style: 'color:red;',
        },
        '删除后用户信息将被清除',
    ),
    onOk() {
      ajax.post('/demo/userChange/delUser', {'id': id}).then(res => {
            if (res.data.code === 200) {
              getUserInfo()

            } else {
              notification['error']({
                message: '失败提示',
                description: res.data.msg,
              });
            }
          }
      )
    },
    onCancel() {
      console.log('Cancel');
    },
    class: 'test',
  });
};

const setRole = (id, role) => {
  const roleMap = {'admin': '管理员', 'user': '普通用户', 'tour': '游客'}
  Modal.confirm({
    title: '确认要调整角色吗？',
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode(
        'div',
        {
          style: 'color:red;',
        },
        '用户角色将被调整为：' + roleMap[role],
    ),
    onOk() {
      ajax.post('/demo/userChange/setRole', {'id': id, 'roleName': role}).then(res => {
            if (res.data.code === 200) {
              getUserInfo()

            } else {
              notification['error']({
                message: '失败提示',
                description: res.data.msg,
              });
            }
          }
      )
    },
    onCancel() {
      console.log('Cancel');
    },
    class: 'test',
  });


}
</script>

<template>
  <a-table :columns="columns" :data-source="data">
    <template #headerCell="{ column }">
      <template v-if="column.key === 'id'">
        <span>
          <smile-outlined/>
          用户ID
        </span>
      </template>
    </template>

    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'name'">
        <a>
          {{ record.name }}
        </a>
      </template>
      <template v-else-if="column.key === 'isActive'">
        <span>
          <a-badge v-if="record.isActive === 1" status="success" text="正常"/>
          <a-badge v-else status="error" text="异常"/>
        </span>
      </template>
      <template v-else-if="column.key === 'loginTime'">
        <span>
          {{ formatDateTime(record.loginTime) }}
        </span>
      </template>
      <template v-else-if="column.key === 'action'">
        <span>
          <a v-if="record.isActive === 1" @click="changeAccount(record.id, record.isActive)">禁用</a>
          <a v-else @click="changeAccount(record.id, record.isActive)">启用</a>
          <a-divider type="vertical"/>
          <a @click="delAccount(record.id)">删除</a>
          <a-divider type="vertical"/>
          <a v-if="record.roleName == 'admin'" style="color: grey">转管理员</a>
          <a v-else @click="setRole(record.id, 'admin')">转管理员</a>
          <a-divider type="vertical"/>
          <a v-if="record.roleName == 'user'" style="color: grey">转普通用户</a>
          <a v-else @click="setRole(record.id, 'user')">转普通用户</a>
          <a-divider type="vertical"/>
          <a v-if="record.roleName == 'tour'" style="color: grey">转游客</a>
          <a v-else @click="setRole(record.id, 'tour')">转游客</a>
        </span>
      </template>
    </template>
  </a-table>
</template>

<style scoped>

</style>